package cloud.xiguapi.ubas.service.impl;

import cloud.xiguapi.ubas.analysis.uv.BloomUVAnalysis;
import cloud.xiguapi.ubas.common.ApiResult;
import cloud.xiguapi.ubas.common.Pager;
import cloud.xiguapi.ubas.entity.BloomUV;
import cloud.xiguapi.ubas.exceptions.ApiException;
import cloud.xiguapi.ubas.service.IUVService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.Jedis;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @author 大大大西西瓜皮🍉
 * date: 2021-5-20 下午 04:02
 * desc:
 */
@Service("bloomUVService")
@Slf4j
@Transactional(readOnly = true, rollbackFor = ApiException.class)
public class BloomUVServiceImpl implements IUVService<BloomUV> {

    public static final String HOST = "localhost";
    public static final int PORT = 6379;
    public static final String KEY = "uv_count";
    private final BloomUVAnalysis bloomUVAnalysis;
    private final Jedis client = new Jedis(HOST, PORT);

    @Autowired
    public BloomUVServiceImpl(BloomUVAnalysis bloomUVAnalysis) {
        this.bloomUVAnalysis = bloomUVAnalysis;
    }

    @Override
    public ApiResult<Pager<BloomUV>> selectPage(long current, long size) {
        return ApiResult.success(Pager.<BloomUV>builder().build());
    }

    public ApiResult<Pager<BloomUV>> select() {
        log.info("基于布隆过滤器的UV统计查询, 查询REDIS({}, {}), KEY = {}", HOST, PORT, KEY);

        List<BloomUV> uvs = new ArrayList<>();
        Map<String, String> uvCountMap = client.hgetAll(KEY);
        uvCountMap.keySet().forEach(windowEnd -> uvs.add(BloomUV.builder()
                .windowEnd(windowEnd)
                .cnt(Long.valueOf(uvCountMap.get(windowEnd)))
                .build()));

        return ApiResult.success(Pager.<BloomUV>builder()
                .current(1)
                .size(uvs.size())
                .total(uvs.size())
                .records(uvs)
                .build());
    }

    @Override
    public ApiResult<Object> analysis(String path) {
        log.info("基于布隆过滤器的UV统计分析, 参数: path = {}", path);
        try {
            bloomUVAnalysis.analysis(path);
            return ApiResult.success(Optional.empty(), "基于布隆过滤器的UV统计分析完成");
        } catch (Exception e) {
            log.error("基于布隆过滤器的UV分析失败, 原因:\n {}", e.getMessage());
            return ApiResult.failed("基于布隆过滤器的UV统计分析失败");
        }
    }
}
